import UIKit
import TF_inviteView
import SDWebImage
class TF_LivingController: UIViewController,TalkfunSDKLifeLiveDelegate,TF_LivingSetCenterDelegate,TF_AnnounceRollViewDelegate,TF_ChatRecordDelegate,TF_LivingVoteViewDelegate,TF_SignInDelegate,TFLotteryViewControllerDelegate ,TFMyLotteryViewControllerDelegate,TF_PublicityViewDelegate,TF_CourseDownLoadDetailDelegate,TalkfunPreventCheatCountdownViewDelegate {

    

    ///【字段含义】访问令牌 [必填]，
    @objc public var access_token:NSString = ""
    
    var TF_navigationBarHidden:Bool = true
    
    let livingSDK = TalkfunSDKLifeLive.sharedInstance()
    let superView = UIView()
    /**聊天输入工具栏*/
    let chatBarView = TF_LivingChatBar()
    /**提示直播间*/
    let joinMember = TF_JoinMember()
    /**语音直播*/
    let voiceLive = TF_VoiceLive.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    /**设置中心*/
    let setCenter = TF_LivingSetCenter()
    /**菜单入口*/
    let pull_upView = TF_Pull_upView()
    /**导航栏*/
    let navigationBar = TF_LivingNavigationBar()
    var isMove:Bool = false
    
    var TF_isStatusBarHidden:Bool = false
    
    /**背景图*/
    let backgroundColorImageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    /**榜单列表*/
    let invitationListView = TF_LivingInvitationListView()
    /**弹窗*/
    let tfAlertView = TF_LivingAlertView()
    /**轮播图片*/
    let rotatePictures = TF_RotatePictures()
    /**推送的广告*/
    let popupPutView = TF_PopupPutView()
    /**宣传图*/
    let publicityView = TF_PublicityView()
    /**图片下载管理者*/
    let imageManage = SDWebImageManager.shared
    /**商品数组*/
    let goodsArray = NSMutableArray()
    /**推荐的商品列表*/
    let recommendList = NSMutableArray()
    /**公告*/
    let announcementView = TF_LivingAnnouncement()
    /**签到*/
    let signInView = TF_SignIn()
    /**投票管理*/
    let voteView = TF_LivingVoteView()
    //信息采集
    let formationCollectionView = TF_informationCollectionView()
    /**奖品名称*/
    var prize_name:NSString = ""
    /**视频容器*/
    let cameraContainerView = UIView()
    /**桌面分享容器*/
    let desktopContainerView = UIView()
    /**暖场视频*/
    let warmupContainerView = UIView()
    let inviteView = TF_inviteView()
    

    private var preventCheatCountdown = TalkfunPreventCheatCountdown()

    /**抽奖开始*/
    private var _lotteryVC: TFLotteryViewController?
    private var lotteryVC: TFLotteryViewController? {
         set {
             _lotteryVC = newValue
        }
        get {
             if _lotteryVC == nil {
                 _lotteryVC = TFLotteryViewController()
                 _lotteryVC!.view.frame = self.view.frame;
                 _lotteryVC!.delegate = self;
                 _lotteryVC!.deleteBtn.addTarget(self, action:#selector(self.deleteBtnClicked), for: .touchUpInside)

            }
           return _lotteryVC
       }
    }
    /**显示中奖人*/
    private var _myLotteryVC: TFMyLotteryViewController?
    private var myLotteryVC: TFMyLotteryViewController?
    {
        set {
            _myLotteryVC = newValue
       }
       get {
            if _myLotteryVC == nil {
                _myLotteryVC = TFMyLotteryViewController()
                _myLotteryVC!.view.frame = self.view.frame;
                _myLotteryVC!.delegate = self;
           }
          return _myLotteryVC
      }
    }
     /**中奖人列表*/
    private var _listLotteryVC: TFLotteryWinnerListViewController?
    private var listLotteryVC: TFLotteryWinnerListViewController?
        {
            set {
                _listLotteryVC = newValue
           }
           get {
                if _listLotteryVC == nil {
                    _listLotteryVC = TFLotteryWinnerListViewController()
                    _listLotteryVC!.view.frame = self.view.frame;
                    _listLotteryVC!.closeBtn.addTarget(self, action: #selector(self.closelistLotterVC), for: .touchUpInside)
               }
              return _listLotteryVC
          }
        }

    /**快速答题卡*/
    private var _answerCard: TF_AnswerCardView?
    private var answerCard: TF_AnswerCardView?
    {
        set {
            _answerCard = newValue
       }
       get {
            if _answerCard == nil {
                _answerCard = TF_AnswerCardView()
                _answerCard!.frame = CGRect(x: (self.view.frame.size.width-325)/2.0, y: (self.view.frame.size.height-200)/2.0, width: 325, height: 200)
                _answerCard!.backgroundColor = UIColor.white
                //灰色阴影
                _answerCard!.layer.shadowOffset = CGSize(width: 1, height: 1)
              
                _answerCard!.layer.shadowOpacity = 0.3;
                _answerCard!.layer.shadowColor = UIColor.lightGray.cgColor
                _answerCard?.fastPaperDetailsSelectBlock = { [weak self] (subjectId ,answerList ,access_key ,msg) in
                guard let `self` = self else { return }

                     let model = TFFillExaminationAnswersParam()
                    model.subjectId = subjectId;
                    model.answerList = answerList;
                    model.type = TFExaminationTypeQuickAnswer;
                    model.access_key = access_key as String
                    self.livingSDK.fillExaminationAnswers(model) {[weak self] (code1, error1) in
                        guard let `self` = self else { return }
                       
                        if (code1 == 0) {
                            self.answerCardSubmitSuccessful()

                        } else {
                            self.TF_toast( error1!.msg )
                        }
                    }
                    
                    
                    
                };

                _answerCard!.closeBlock = { [weak self]  in
                    guard let `self` = self else { return }
                    self.removeAnserCard()
                    
                };
                _answerCard!.endBlock = { [weak self]  in
                    guard let `self` = self else { return }
                    self.endAnswerCardView()
                   
                };
                
           }
          return _answerCard
      
    }
    }

    func removeAnserCard()
    {
        self.answerCard?.removeFromSuperview()
        self.answerCard = nil;
    }
    func answerCardSubmitSuccessful()
    {
        self.answerCard!.frame = CGRect(x: (self.view.frame.size.width-150)/2.0, y: (self.view.frame.size.height-150)/2.0, width: 150, height: 150)
      
        self.answerCard!.answerView.isHidden = true;
        self.answerCard!.answerSuccessView.isHidden = false
        self.answerCard!.startAnswerCardSuccessTimers()

    }
    var leftRecognizer:UISwipeGestureRecognizer?
    
    var rightRecognizer:UISwipeGestureRecognizer?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if self.navigationController != nil {
            self.TF_navigationBarHidden = self.navigationController!.isNavigationBarHidden
            self.navigationController!.isNavigationBarHidden = true
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled =  false
        }
        
        
        self.leftRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(TF_LivingController.leftRecognizerTouchesBegan))
        self.leftRecognizer?.direction = .left
        
        self.rightRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(TF_LivingController.rightRecognizerTouchesBegan))
        self.rightRecognizer?.direction = .right
   
        let keyWindow = TalkfunSharedTools.keyWindow()
  
            keyWindow.addGestureRecognizer(self.leftRecognizer!)
            keyWindow.addGestureRecognizer(self.rightRecognizer!)
        
        
        
        self.view.backgroundColor = UIColor.white

        self.backgroundColorImageView.contentMode = .scaleToFill;
        self.backgroundColorImageView.image = UIImage.init(named: "HTLive.bundle/LivingackgroundColorImageView")
        self.backgroundColorImageView.frame = TalkfunSharedTools.getMainScreen()
        self.view.addSubview(self.backgroundColorImageView)
     
        self.superView.frame = TalkfunSharedTools.getMainScreen()
        self.view.addSubview(self.superView)
        //TODO:初始化SDK
        self.livingSDK.delegate = self;
        self.livingSDK.scalingMode = .fill;
        //配置初始化参数
        let params = TalkfunSDKLifeLiveInitParams()
        params.accessToken = self.access_token as String;
        params.videoBgColor = .clear
        //进入房间
        self.livingSDK.enterRoom(params)
//        self.livingSDK.picture(inPicture: true)
        //TODO:配置摄像头容器
        self.cameraContainerView.frame = self.superView.bounds
        self.cameraContainerView.backgroundColor = UIColor.clear
        self.superView.addSubview(self.cameraContainerView)
        self.livingSDK.configureCameraContainerView(self.cameraContainerView)
        
         //TODO:语音直播中
        self.voiceLive.isHidden = true
        self.voiceLive.frame = self.superView.bounds
        self.superView.addSubview(self.voiceLive)
        
        //TODO:桌面分享容器  
        self.desktopContainerView.isHidden = true;
        self.desktopContainerView.isUserInteractionEnabled = false
        self.desktopContainerView.backgroundColor = UIColor.black
        self.desktopContainerView.frame = self.superView.bounds
        self.superView.addSubview(self.desktopContainerView)
        self.livingSDK.configureDesktopContainerView(self.desktopContainerView)
        
        //TODO:暖场视频
        self.warmupContainerView.isHidden = true
        self.warmupContainerView.isUserInteractionEnabled = false
        self.warmupContainerView.backgroundColor = UIColor.clear
        self.warmupContainerView.frame = self.superView.bounds;
        self.superView.addSubview(self.warmupContainerView)
        self.livingSDK.configureWarmupContainerView(self.warmupContainerView)
        
        //TODO: 用户进入显示
         self.joinMember.frame = CGRect(x: 0, y:  -1000, width: 0, height: 0)
        self.view.addSubview(self.joinMember)
        //TODO:导航view
        if (self.isNotchScreen) {
            self.navigationBar.mNavigationbarHeight = 32
         }
        self.navigationBar.frame = self.superView.bounds;
        self.navigationBar.view.frame = self.navigationBar.bounds;
        self.superView.addSubview(self.navigationBar)
        //TODO:邀请榜单点击事件
        self.navigationBar.invitationList.addTarget(self, action: #selector(self.invitationListClick), for: .touchUpInside)
     
      //TODO:退出直播间事件
        self.navigationBar.livingClose.addTarget(self, action: #selector(self.livingCloseClick), for: .touchUpInside)
      //TODO:刷新事件
        self.navigationBar.livingRefresh.addTarget(self, action: #selector(self.livingRefreshClick), for: .touchUpInside)

         //TODO:关注事件
        self.navigationBar.attentionButton.addTarget(self, action: #selector(self.attentionButtonClick), for: .touchUpInside)

         self.navigationBar.announceRollView.delegate = self
        //TODO:设置中心
         self.setCenter.delegate = self
         self.setCenter.chatRecord.delegate = self
         self.setCenter.frame = self.superView.bounds;
         self.superView.addSubview(self.setCenter)
         self.setCenter.setUI()
        //TODO:八宫格点击事件
        self.setCenter.moreConfiguration.buttonAddTarget(target: self, action: #selector(self.moreConfigurationClick))
        //TODO:拉起菜单入口事件
        self.setCenter.livingTool.pull_up.addTarget(self, action: #selector(self.pull_upClick), for: .touchUpInside)
        //TODO:发送提问事件
        self.setCenter.ask.askBtn.addTarget(self, action: #selector(self.enterAskQuestions), for: .touchUpInside)
        //TODO:确定发送举报数据事件
        self.setCenter.reportView.end.addTarget(self, action: #selector(self.endSend), for: .touchUpInside)
        //TODO: 发送内容给客服发送事件
        self.setCenter.service.sendBlock = { [weak self] (xid ,msg) in
            guard let `self` = self else {
                return
            }
            //发送私聊
            self.livingSDK.sendChatPrivate(xid as String, msg: msg as String) { [weak self] (code, data, error) in
                guard let `self` = self else {
                    return
                }
                if (code == 0 ) {
                self.setCenter.service.textField.text = "";
                self.setCenter.service.addChatUI(chat: data!, xid: xid)
                }else{
                    self.TF_toast( error!.msg)
                }
                
            }
            
        }
        
        //TODO: 发送图片给客服发送事件
        self.setCenter.service.photoSend.addTarget(self, action: #selector(self.photoSendClick), for: .touchUpInside)

        //TODO:邀请榜单列表窗口
        self.invitationListView.frame = self.superView.bounds;
        self.superView.addSubview(self.invitationListView)
        self.invitationListView.setUI()

        //TODO:菜单入口VIEW
        self.pull_upView.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
        let pull_upViewHight:CGFloat = 397
        self.pull_upView.frame = CGRect(x: 0, y: self.superView.frame.size.height, width: self.superView.frame.size.width, height: pull_upViewHight)
        self.superView.addSubview(self.pull_upView)
        self.pull_upView.initMask()

        //宣传图
        self.publicityView.frame = self.superView.bounds;
        self.superView.addSubview(self.publicityView)
        self.publicityView.delegate = self;
        self.publicityView.setUI()

        //TODO:点赞事件
        self.setCenter.livingTool.love.addTarget(self, action: #selector(self.praiseAnimation), for: .touchUpInside)

        //TODO:打开宝_贝链接 打开宝贝列表事件
        self.setCenter.livingTool.livingaBby.addTarget(self, action: #selector(self.livingaBbyClick), for: .touchUpInside)
       
         //TODO:聊天输入工具栏
        self.chatBarView.bottom.alpha = 0;
        self.chatBarView.expression.isSelected = false
        self.chatBarView.frame = CGRect(x: 0, y: TalkfunSharedTools.getMainScreen().size.height, width: self.superView.frame.size.width, height: 253)
        self.superView.addSubview(self.chatBarView)
        //TODO:发送聊天数据事件
        self.chatBarView.sendButton.addTarget(self, action: #selector(self.sendButtonClcik), for: .touchUpInside)

        //TODO:抽奖中事件
        self.setCenter.lotteryCall.addTarget(self, action: #selector(self.lotteryCallClick), for: .touchUpInside)
        //TODO:点名中事件
        self.setCenter.rollCall.addTarget(self, action: #selector(self.rollCallClick), for: .touchUpInside)
        //邀请卡
        self.setCenter.inviteEntrance.addTarget(self, action: #selector(self.getInvitationCardClick), for: .touchUpInside)
        //信息采集
        self.setCenter.informationCollection.addTarget(self, action: #selector(self.informationCollectionClick), for: .touchUpInside)
        //TODO:投票列表
        self.setCenter.voteButton.addTarget(self, action: #selector(self.voteButtonClick), for: .touchUpInside)

        //TODO:宣传图
        self.setCenter.publicityBtn.addTarget(self, action: #selector(self.publicityClick), for: .touchUpInside)
      
        //TODO:实时的推送广告
        self.popupPutView.mNavigationbarHeight = self.navigationBar.mNavigationbarHeight
        self.popupPutView.frame = self.superView.bounds;
        self.superView.addSubview(self.popupPutView)
        //TODO: 聊天的图片轮播
        self.rotatePictures.frame = self.superView.bounds;
        self.rotatePictures.mNavigationbarHeight = self.navigationBar.mNavigationbarHeight;
        self.superView.addSubview(self.rotatePictures)
        //TODO:公告
        self.announcementView.alpha = 0
        self.announcementView.backgroundColor = UIColor.clear
        let announcementViewW:CGFloat = 352
        let announcementViewH:CGFloat = 172 + 10
        let announcementViewX:CGFloat = (self.superView.frame.size.width - announcementViewW)/2;
        let announcementViewY:CGFloat = self.navigationBar.invitationList.frame.maxY + 10
        self.announcementView.frame = CGRect(x: announcementViewX, y: announcementViewY, width: announcementViewW, height: announcementViewH)
        self.announcementView.clipsToBounds = true
        self.announcementView.layer.cornerRadius = 10;
        self.superView.addSubview(self.announcementView)

        //TODO:签到View
        self.signInView.delegate = self
        self.signInView.frame = self.superView.bounds
        self.signInView.view.frame = CGRect(x: 0, y: self.signInView.frame.size.height, width: self.signInView.frame.size.width, height: 312)
        self.superView.addSubview(self.signInView)
        //TODO:确定签到事件
        self.signInView.round.addTarget(self, action: #selector(self.roundClick), for: .touchUpInside)

        //TODO:投票view
        self.voteView.delegate = self;
        self.voteView.frame = self.superView.bounds;
        self.superView.addSubview(self.voteView)
        //TODO: 投票列表的返回
        self.voteView.scrollView.backButton.addTarget(self, action: #selector(self.backButtonClick), for: .touchUpInside)

        //TODO:提交投票答案
        self.voteView.scrollView.submit.addTarget(self, action: #selector(self.submitClick), for: .touchUpInside)
        //TODO:提示标语view
        self.tfAlertView.frame = self.superView.bounds;
        self.superView.addSubview(self.tfAlertView)
        self.setCenter.courseDownView.downLoadRoot.delegate = self
        
        self.inviteView.frame = self.superView.bounds
        self.superView.addSubview(self.inviteView)
        
        //------------
        self.formationCollectionView.frame = self.superView.bounds
        self.superView.addSubview(formationCollectionView)
        

    }
    
    @objc func leftRecognizerTouchesBegan()
    {
        if (self.isMove==false ) {
            self.move(false)
        }
    }
    @objc func rightRecognizerTouchesBegan()
    {
        if (self.isMove==true) {
            self.move(true)
        }
    }
    //TODO: 榜单点击
    @objc func invitationListClick()
    {
        self.livingSDK.getInvitationList {[weak self] (code, data, error) in
            guard let `self` = self else { return }
            
            if (code == 0) {
                self.invitationListView.list.removeAllObjects()
                let list:NSMutableArray = data!.list as NSMutableArray
                self.invitationListView.list.addObjects(from: list as! [Any])
        
                self.invitationListView.tableView.reloadData()
              
            }else{
                self.TF_toast(error!.msg)
            }
        }
        self.invitationListView.showView(show: true)
      

    }
    
    @objc func livingCloseClick()
    {
       
        self.view.endEditing(true)
        let alert = UIAlertController.init(title: "提示", message: "确定要退出直播间吗", preferredStyle:.alert)
        let cancel:UIAlertAction = UIAlertAction.init(title: "取消", style: .default) { action in
            
        }
        alert.addAction(cancel)
        let otherAction:UIAlertAction = UIAlertAction.init(title: "确认", style: .default) { action in
            self.exit()
        }
        alert.addAction(otherAction)
        

        if  UIDevice.current.model.hasPrefix("iPad") {
            alert.popoverPresentationController?.sourceView = self.view
            alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        }
        
        self.present(alert, animated: true)

    }
    
    //退出直播间
    func exit()
    {
        self.preventCheatCountdown.remind.stopUI()

        //不再监听键盘
        self.formationCollectionView.destroySharedIntance()
        
        if self.navigationController != nil {
          
            self.navigationController!.isNavigationBarHidden = self.TF_navigationBarHidden
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled = false
        }
        
        let keyWindow = TalkfunSharedTools.keyWindow()
     
            keyWindow.removeGestureRecognizer(self.leftRecognizer!)
            keyWindow.removeGestureRecognizer(self.rightRecognizer!)
        
        
     
        NotificationCenter.default.removeObserver(self)
        
        self.backgroundColorImageView.sd_setImage(with: URL.init(string: ""))
        self.navigationBar.timerStop()
        self.pull_upView.destroy()
        self.livingSDK.destroy()
        self.chatBarView.destroy()
        self.setCenter.recommendView.destroy()
        self.setCenter.destroy()
        self.setCenter.chatRecord.dataSource.removeAllObjects()
        self.signInView.destroySharedIntance()
        self.chatBarView.chatBar.text = ""
        UIView.setAnimationsEnabled(true)
        //返回上一页
        self.TF_dismissUI()
    }
    //TODO: 刷新
    @objc func livingRefreshClick()
    {

        self.view.endEditing(true)
        self.livingSDK.refreshData()
    }

    //TODO: 关注
    @objc func attentionButtonClick()
    {
        self.tfAlertView.attentionView.isHidden = false
    }
    //TODO:  八宫格点击事件
    @objc func moreConfigurationClick(btn:TF_MoreConfigurationButton)
    {
          self.setCenter.moreConfiguration.isShowConfiguration = false
        if (btn.modelType == "提问") {
            self.setCenter.isShowAsk = true
            self.questionBtnClearRedDot()
        }else  if (btn.modelType == "网络选择") {
        self.setCenter.isShowNetworkSelection = true
            ////获取线路网络列表
            self.livingSDK.getLineList {[weak self] (result) in
                guard let `self` = self else { return }
                
                if (result.code == 0) {
                    self.setCenter.networkSelection.refreshData(array: result.data, target: self, action: #selector(self.networkSelectionClick), controlEvents: .touchUpInside)

                }else{
              
                    self.TF_toast(result.msg)
                    
                }
            }
            
       
        }
        
        else  if (btn.modelType == "举报") {
            self.setCenter.isShowReport = true
        }else  if (btn.modelType == "红"+"包记录") {
            
        }else  if (btn.modelType == "提"+"现") {
            
        }else  if (btn.modelType == "客服") {
            self.setCenter.isShowService = true
        }else  if (btn.modelType == "个人中心") {
            self.setCenter.isShowInfo = true
        }else  if (btn.modelType == "商"+"城") {
            let url = self.livingSDK.roomInfo.pageConfig.menu.store.url as NSString
           
            if (url.length>0) {
                TalkfunSharedTools.openUrl(str: url)
               
            }
        }
        else  if (btn.modelType == "课件下载") {
            self.setCenter.isShowCourseDown = true
            self.getCourseDownData()
        }
    }
    
    //TODO: 设置线路
    @objc func networkSelectionClick(button:TF_LivingButton)
    {
        self.setCenter.networkSelection.networkSelectionClick(button: button)
       
        self.livingSDK.setNetwork(button.networkDict.key, selectedSegmentIndex: button.groupIndex) {[weak self] (code, error) in
            guard let `self` = self else { return }
            if(code == 0)
            {
               
                self.TF_toast( String.init(format: "已切换到线路%ld", button.tag+1) )
              
            }else
            {
                self.TF_toast(error!.msg)
               
            }
            
        }
       
    }
    //TODO: 获取下载列表数据
    @objc func getCourseDownData()
    {
        let param = TFdocParam()
        param.page = 1;
        param.accessToken = self.access_token as String
        self.setCenter.courseDownView.downLoadRoot.getCourseDownData(param)
       
    }
    
    //TODO: 拉起菜单入口
    @objc func pull_upClick()
    {
        self.pull_upView.isShow(value: true)
    }
    
    //TODO: 发送提问的数据
    @objc func enterAskQuestions()
    {
//        self.view.endEditing(true)
        //发起提问
        self.livingSDK.enterAskQuestions(self.setCenter.ask.textView.text) {[weak self] (code, data, error) in
            guard let `self` = self else { return }
            if (code == 0 ) {
             self.setCenter.ask.textView.text = "";
            self.setCenter.ask.addQskQuestionsDictUI(model: data!)
            }else
            {
                if let error = error
                {
                    self.TF_toast( error.msg )
                }
               
            }
        }
    
    }
    //TODO: 确定发送举报数据
    @objc func endSend()
    {
        self.view.endEditing(true)
        self.setCenter.isShowReport = false
        var msg = "其它举报原因";
        if (self.setCenter.reportView.msg.length > 0 ) {
            msg = self.setCenter.reportView.msg as String
        }
        self.livingSDK.reportingMembers(msg) {[weak self] (code, error) in
            guard let `self` = self else { return }
            if (code == 0) {
                self.TF_toast("举报成功")
             
            }else{
                self.TF_toast(error!.msg)
            }
            
        }
    
        self.setCenter.reportView.textView.text = "";
        self.setCenter.reportView.msgViewTextLength.text = "0/25"
    }
    
    //#pragma mark 发送图片
  @objc func photoSendClick()
    {
    //    WeakSelf
    //    //图片二
    //   TZImagePickerController *photoPicker = [[TZImagePickerController alloc] initWithMaxImagesCount:2 delegate:nil];
    //    photoPicker.allowPickingVideo = NO;//不要视频
    //    photoPicker.autoDismiss = YES;
    //    photoPicker.maxImagesCount = 1;
    //    photoPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    //    photoPicker.alwaysEnableDoneBtn = 1 ;//至少选中多少 就能完成
    //    //对照片排序，按修改时间升序，默认是YES。如果设置为NO,最新的照片会显示在最前面，内部的拍照按钮会排在第一个
    //    photoPicker.sortAscendingByModificationDate = NO;
    //    photoPicker.isShowBack = YES;
    //    photoPicker.naviBgColor =   [UIColor whiteColor];
    //    photoPicker.naviTitleColor = [UIColor blackColor];
    //
    //
    //    [photoPicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    //
    //        if (photos.count >0 ) {
    //            UIImage *image = photos[0];
    //
    //            [weakSelf.livingSDK uploadingpicImg:image callback:^(NSInteger code, NSString * _Nullable imageUrl, TFError * _Nullable error) {
    //                if (code == 0) {
    //
    //                    NSLog(@"msg======>%@",imageUrl);
    //
    //
    //                }else{
    //                    NSLog(@"msg======>%@",imageUrl);
    //                 [weakSelf.superView toast:error.msg position:];
    //                }
    //            } ];
    //
    //        }
    //
    //        }];
    //    [self presentViewController:photoPicker animated:YES completion:nil];
    }
    //TODO: 点赞
   @objc func praiseAnimation()
    {
        //动画
        self.setCenter.livingTool.praiseAnimation()
       
        //真正数据
        self.livingSDK.likeClick {[weak self] (code, data, error) in
            guard let `self` = self else { return }
            if (code == 0 ) {
                self.setCenter.livingTool.updateTotal(total: data!.times)
            }else{
                self.TF_toast( error!.msg )
            
            }
        }
    }
    
    
    func goodsListViewUI( _ list:NSMutableArray)
    {
        let getGoodsListCount = list.count
        
        self.setCenter.goodsListView.title.text = "商品（" + (NSString.init(format: "%lu", getGoodsListCount) as String) + "个）"
        
        self.setCenter.livingTool.livingaBbyLabel.text = (NSString.init(format: "%lu", getGoodsListCount) as String)
        //-----------------------------------
        self.setCenter.goodsListView.list.removeAllObjects()
        self.setCenter.goodsListView.list.addObjects(from: self.getGoodsList() as! [Any])
        self.setCenter.goodsListView.tableView.reloadData()
    }
    //TODO: 宝贝 列表
    @objc func livingaBbyClick()
    {
        if (self.livingSDK.roomInfo.pageConfig.store.type == 1) {
            self.setCenter.isShowGoodsListView = true
            
        
            self.goodsListViewUI(self.getGoodsList())

         
        }
        else  if (self.livingSDK.roomInfo.pageConfig.store.type == 2)  {
         
            let url:NSString = self.livingSDK.roomInfo.pageConfig.store.url as NSString
//            NSLog(@"外宝贝链接%@",url);
            if ((url.length) != 0) {
                TalkfunSharedTools.openUrl(str: url)
               
            }
           
        }
        else if (self.livingSDK.roomInfo.pageConfig.store.type == 3)
        {
            
            let url:URL? = URL.init(string: self.livingSDK.roomInfo.pageConfig.store.qrcode as String)
            self.tfAlertView.qrcodeStore.QRView.sd_setImage(with: url, completed: nil)
            
            self.tfAlertView.qrcodeStore.title.text = "长按二维码保存到相册\n用微信扫描进入商城";
            self.tfAlertView.qrcodeStore.isHidden = false
        }
        
    }
    //TODO: 获取上架与推荐的商品
    @objc func getGoodsList()->NSMutableArray
    {
        self.goodsArray.removeAllObjects()
        for i in 0..<self.livingSDK.roomInfo.pageConfig.store.goods.count {
          let goods = self.livingSDK.roomInfo.pageConfig.store.goods[i] as! TFgoods
            
            if (goods.putaway == TalkfunPutawayOn || goods.putaway == TalkfunPutawayRecommendOn) {
                self.goodsArray.add(goods)
            }
           
        }
        return self.goodsArray;
    }
    //获取推荐的商品
    @objc func getRecommendList()->NSMutableArray
    {
        self.recommendList.removeAllObjects()
      
        for i in 0..<self.livingSDK.roomInfo.pageConfig.store.goods.count {
            let goods = self.livingSDK.roomInfo.pageConfig.store.goods[i] as! TFgoods
            // 推荐商品
            if (goods.putaway == TalkfunPutawayRecommendOn) {
                self.recommendList.add(goods)
              
            }
           
        }
        return self.recommendList;
    }
    //TODO:  发送聊天
    @objc func sendButtonClcik()
    {
        self.view.endEditing(true)
        //直播未开始
        if self.livingSDK.roomInfo.liveStatus == TalkfunLiveStatusWait && self.livingSDK.roomInfo.mod_beforeclass_live.config.chat.enable == false {
            self.TF_toast("课前禁止聊天互动")
            return
        }
        if self.livingSDK.roomInfo.liveStatus == TalkfunLiveStatusStop && self.livingSDK.roomInfo.mod_afterclass_live.config.chat.enable == false {
            self.TF_toast("课后禁止聊天互动")
            return
        }
        self.livingSDK.sendChat(self.chatBarView.chatBar.text) {[weak self] (code, data, error) in
            guard let `self` = self else { return }
            
            if (code == 0 ) {
                if self.chatBarView.chatBar.isFirstResponder == false {
                    self.chatBarView.keyboardWillHideUI(0.5)
                }
                
                
                self.chatBarView.chatBar.text = ""
                self.chatBarView.chatBar.setNeedsDisplay()
                
                self.addChatData(chatData: TalkfunSharedTools.getLivingChatData(dict: data!))
            
            }else{
                
                    if let error = error
                    {
                        self.TF_toast( error.msg )
                    }
                   
                
            
            }
            
        }
       
    }

    func addChatData(chatData:TFChatData)
    {
        let imageURL:NSString =  chatData.imageURL as NSString
        
        if (imageURL.length>0) {
            
            self.imageManage.loadImage(with: URL.init(string: imageURL as String), options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

            } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
                guard let `self` = self else {
                    return
                }

                DispatchQueue.main.async {

                    if (image != nil)
                    {
                        
                        let model = TalkfunSharedTools.getLivingChatData(dict: chatData)
                        model.image = image!;
                        self.addModel(model: model)
                        self.rotatePictures.addPictures(model: model)
                   
                    }
                  

                }
            }

        }else{
            self.addModel(model: TalkfunSharedTools.getLivingChatData(dict: chatData))
          
        }
    }

    func addModel(model:TF_LivingChatData)
    {
        if (self.setCenter.chatRecord.dataSource.count > 150) {
            self.setCenter.chatRecord.dataSource.removeObject(at: 0)
         
        }
        self.setCenter.chatRecord.dataSource.add(model)
   
        
        var chatRecordH:CGFloat = self.setCenter.chatRecord.frame.size.height
        var cellHeight:CGFloat = 0
        for i in 0..<self.setCenter.chatRecord.dataSource.count {
  
            cellHeight = cellHeight + self.setCenter.chatRecord.getCellHeight(row: i)
        }
        //所有cell 叠加的高度 <
        if (cellHeight<chatRecordH) {
             self.setCenter.chatRecord.tableView.isUserInteractionEnabled = false
            chatRecordH = cellHeight;
            self.setCenter.chatRecord.scrollView.isScrollEnabled = true
        }else{
            chatRecordH = self.setCenter.chatRecord.frame.size.height;
            self.setCenter.chatRecord.scrollView.isScrollEnabled = false
            self.setCenter.chatRecord.tableView.isUserInteractionEnabled = true
        }
        let chatRecordY:CGFloat = self.setCenter.chatRecord.frame.size.height - chatRecordH
        
         self.setCenter.chatRecord.tableView.frame = CGRect(x: 0, y: chatRecordY, width: self.superView.frame.size.width, height: chatRecordH)
        self.setCenter.chatRecord.tableViewReloadData()
    }
    //#pragma mark  删除聊天事件回调
    public func onChatDel(_ uuid: String) {
        
        for i in 0..<self.setCenter.chatRecord.dataSource.count {
       let model = self.setCenter.chatRecord.dataSource[i] as!TF_LivingChatData

            if model.uuid == uuid {
                self.setCenter.chatRecord.dataSource.remove(model)
               
                break
            }
            
        }
        
        var chatRecordH:CGFloat = self.setCenter.chatRecord.frame.size.height;
        var cellHeight:CGFloat = 0
        for i in 0..<self.setCenter.chatRecord.dataSource.count {
            
            cellHeight = cellHeight + self.setCenter.chatRecord.getCellHeight(row: i)
        }
        //所有cell 叠加的高度 <
        if (cellHeight < chatRecordH) {
             self.setCenter.chatRecord.tableView.isUserInteractionEnabled = false
            chatRecordH = cellHeight;
             self.setCenter.chatRecord.scrollView.isScrollEnabled = true
        }else{
            chatRecordH = self.setCenter.chatRecord.frame.size.height;
            self.setCenter.chatRecord.scrollView.isScrollEnabled = false
            self.setCenter.chatRecord.tableView.isUserInteractionEnabled = true
        }
        let chatRecordY:CGFloat = self.setCenter.chatRecord.frame.size.height - chatRecordH
         self.setCenter.chatRecord.tableView.frame = CGRect(x: 0, y: chatRecordY, width: self.superView.frame.size.width, height: chatRecordH)
        self.setCenter.chatRecord.tableViewReloadData()

    }
   // #pragma mark  接收别人的聊天事件回调
    public func onDidReceiveText(_ result: TFChatData) {
        
        self.addChatData(chatData: result)
    }

    //#pragma mark 直播间状态
    func onLiveStatus(_ status: TalkfunLiveStatus) {
        let videoUrl:NSString = self.livingSDK.roomInfo.videoUrl as NSString
        //直播结束
         if (status == TalkfunLiveStatusStop) {
             self.preventCheatCountdown.remind.isShow = false
             self.preventCheatCountdown.remind.view.isHidden = true
             self.preventCheatCountdown.remind.successView.isHidden = true
             //---------------------
             
             self.voiceLive.isHidden = true
        
             if (videoUrl.length > 0 &&  TalkfunSharedTools.getCurrentDateString() < self.livingSDK.roomInfo.end_time ) {
                 self.warmupContainerView.isHidden = false
             }else{
                 
                 self.warmupContainerView.isHidden = true
                 self.cameraContainerView.isHidden = true
                 self.navigationBar.liveBroadcastClosed(hidde: false)
    
                 self.voiceLive.isHidden = true;
                
                 self.navigationBar.adListView.isHidden = true;
                 //主播暂时不在
                 self.navigationBar.leaveTemporarilyLabel.isHidden = true;
             }
             
                 if(self.preventCheatCountdown.remind.countdownTime != nil)
                  {
                     self.preventCheatCountdown.remind.countdownTime?.invalidate()
                     self.preventCheatCountdown.remind.countdownTime = nil
                 }

             
        }else {
            //直播未开始
            if (status == TalkfunLiveStatusWait)
            {
                
                if (videoUrl.length > 0 ) {
                    self.warmupContainerView.isHidden = false
                }
                self.navigationBar.liveBroadcastClosed(hidde: true)
             
                
                    //  当前时间 大于   开始时间课程
                if (TalkfunSharedTools.getCurrentDateString() > self.livingSDK.roomInfo.startTime ) {

                    //主播暂时不在
                    self.navigationBar.leaveTemporarilyLabel.isHidden = false;

                    self.navigationBar.dateContentLabel.isHidden = true;
                    self.navigationBar.clocKLabel.isHidden = true;
                    self.navigationBar.clocKButton.isHidden = true;
                    
                }else{
                    //日期内容
                    self.navigationBar.setDateContent(startTime: self.livingSDK.roomInfo.startTime)
                    
              
                    // 直播倒计时 是否显示
                         if (self.livingSDK.roomInfo.pageConfig.countDown.enable == true ) {
                             self.navigationBar.dateContentLabel.isHidden = false
                             self.navigationBar.clocKLabel.isHidden = false
                             self.navigationBar.clocKButton.isHidden = false
                         }else{
                             self.navigationBar.dateContentLabel.isHidden = true
                             self.navigationBar.clocKLabel.isHidden = true
                             self.navigationBar.clocKButton.isHidden = true
                         }
                }
             
            }//直播开始
            else if (status == TalkfunLiveStatusStart) {
                self.warmupContainerView.isHidden = true;
                self.cameraContainerView.isHidden = false;
                self.navigationBar.liveStarted()

                //获取提问列表
                self.livingSDK.getAList {[weak self] (code, list, error) in
                    guard let `self` = self else { return }
                    
                    if (code == 0) {

                        self.setCenter.ask.updatedQuestionListUI(array: list!)
                    }
                }
               
                //TODO:浮动广告列表
                self.navigationBar.adListView.isHidden = false
              
            }
        }
    }
    func mNavigationbarHeight()->CGFloat
    {
        if self.navigationController != nil {
            return self.navigationController!.navigationBar.frame.size.height
        }
        return 0
        
    }
    //TODO: 正在抽奖
    @objc func lotteryCallClick()
    {
        let model = TFLotteryStart()
        
        self.onLotteryStart(model)
    }
    //信息采集事件
    @objc func informationCollectionClick()
    {
        
        self.formationCollectionView.isShow(true)
        
        
        
    }
    @objc func getInvitationCardClick()
    {
  
        self.livingSDK.getInvitationCard {[weak self] (code, model, error) in
            guard let `self` = self else { return }
            
            if (code == 0) {
                let new_model = skinModel()
                //选择第1个
                new_model.state = 1;
                //用户头像
                new_model.avatar = model!.avatar;
                //用户名字
                new_model.nickname = model!.nickname;
                //课程二维码
                new_model.qrcodeUrl = model!.qrcodeUrl;
                //宣传内容
                new_model.descriptionMsg = model!.descriptionMsg;
                //直播开始时间
                new_model.startingTime = model!.course.start_time;
                //举办方
                new_model.company = model!.zhubo.nickname;
                //标题
                new_model.title = model!.title;
                //导航栏
                new_model.isShowNavigationBar = true;
                self.inviteView.setCurrent(new_model, viewController: self)
               
              
            }else{
                self.TF_toast(error!.msg)
            }
        }
    }
    
    //TODO: 弹起点名窗口
   @objc func rollCallClick()
    {
        self.superView.addSubview(self.signInView)
        UIView.animate(withDuration: 0.5) {
     
            self.signInView.view.frame = CGRect(x: 0, y: self.signInView.frame.size.height - self.signInView.view.frame.height, width: self.signInView.frame.size.width, height: self.signInView.view.frame.height)

        }
    }
    
    //TODO:  获取投票列表----------------------------------------------
    @objc func voteButtonClick()
    {
        self.livingSDK.getVotingList {[weak self] (code, list, error) in
            guard let `self` = self else { return }

            if (code == 0 ) {
                if (list!.count == 0 ) {
                    self.setCenter.voteButton.isHidden = true
                    self.voteView.isShowScrollView(show: false)
                  
                   
                }else{
                    self.setCenter.voteButton.isHidden = false
                }
                self.setCenter.layoutSubviews()
                self.voteView.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
                
                self.voteView.setVoteListUI(list: list!)
             
             
            }else{
                self.TF_toast( error!.msg )
              
            }
        }
    }
    
    //TODO: 宣传图显示
    @objc func publicityClick()
    {
        //只有一个宣传图
        if self.livingSDK.roomInfo.pageConfig.popUp.count==1 {
        let model = self.livingSDK.roomInfo.pageConfig.popUp[0] as! TFPopupPut
            
        // 默认宣传图 && 存在链接
        if (model.pupUpType == 0 &&  model.url.count>0) {
                
                if #available(iOS 10.0, *) {
                    let newURL = NSURL.init(string:model.url as String)
                    UIApplication.shared.open(newURL! as URL, options: [:], completionHandler: nil)
                }
                
            }else
            {
                self.checkPuplicityImg(model)
            }
            return
        }
        self.publicityView.updateData(self.livingSDK.roomInfo.pageConfig.popUp)
        self.publicityView.showView(!self.publicityView.isShow)
    }
    //TODO:  学员确认签到的事件
    @objc func roundClick()
    {
        self.livingSDK.sign(in: self.signInView.result!.signId) { [weak self] (code, error) in
            guard let `self` = self else { return }
            
            if (code == 0 ) {
                self.setCenter.rollCall.isHidden = true
                self.setCenter.layoutSubviews()
                self.signInView.roundClickUI()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                    self.signInView.onSignEndUI(result: TFSignEnd())
                    }
               
            }else{
                self.TF_toast(error!.msg )
               
            }
        }
    }
    
    //TODO: 返回
    @objc func backButtonClick()
    {
        self.voteButtonClick()
        self.voteView.scrollView.backButtonClickUI()
      
    }

    //TODO: 公共广播
    public func onBroadcast(_ result: TFBroadcast) {
        let model = TF_LivingChatData()
        model.time = result.time
        model.gid = result.gid
        model.msg = result.msg
        model.isBroadcast = true
        self.addModel(model: model)
    }
    //TODO: 监听别人的点赞
    func onLikePut(_ likeData: TFLikeData) {
        self.setCenter.livingTool.updateTotal(total: likeData.times)
    }
    //TODO:  接收客服的内容的回调
    func onChatPrivate(_ result: TFChatData) {
        self.setCenter.service.addChatUI(chat: result, xid: result.xid as NSString)
        
        
        self.setCenter.livingTool.more.drawRedDot()
        //刷新未读
        self.unreadUI()
        
        //看了部份未读, 再刷新
        self.setCenter.service.unreadBlock = { [weak self] () in
            guard let `self` = self else { return }
            self.unreadUI()
        }
    }
    //TODO:  在线客服列表变更时会实时更新列表
    func onCustomerServiceListUpdate(_ list: NSMutableArray) {
        self.setCenter.service.updateXidUI(list: list)
    }
    //TODO:  有人退出房间
    func onMemberLeave() {
        
    }
    //TODO: 其它人进入房间触发
    func onMemberJoinOther(_ result: TFMember) {
        //入场提示
        if (self.livingSDK.roomInfo.pageConfig.entranceTips.enable) {
            self.joinMember.joinMemberList.add(result)

                self.joinMember.timeFireMethod(Y: self.setCenter.chatRecord.frame.origin.y)
               
            }
    }
    //TODO: ----------当前用户进入房间触发----------
    func onMemberJoinMe(_ result: TFMember) {
        if (self.livingSDK.roomInfo.pageConfig.entranceTips.enable ) {
            self.joinMember.joinMemberList.add(result)
            self.joinMember.timeFireMethod(Y: self.setCenter.chatRecord.frame.origin.y)
        }
    }
    //TODO: 同时在线人数
    func onPeakConcurrentUsers(_ total: Int) {
        //显示访客人数  (要sdk 开启)
        if (self.livingSDK.roomInfo.pageConfig.number.enable && self.livingSDK.roomInfo.visitors) {
            self.navigationBar.viewersLabel.isHidden = false
        }else{
            self.navigationBar.viewersLabel.isHidden = true
        }
        var msg = " 观看"
        //开启观看人数
        if (self.livingSDK.roomInfo.pageConfig.number.popularity.enable) {
            msg = " 人气";
        }
        
        let viewersLabelText = (NSString.init(format: "%li", total) as String) + msg
        self.navigationBar.viewersLabel.text = viewersLabelText
        

       
        let focusStrAttrsSize: CGSize = viewersLabelText.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 10) as Any])
        

        let nicknameLabelText:NSString = self.navigationBar.nicknameLabel.text! as NSString

        
        let nicknameLabelAttrsSize: CGSize = nicknameLabelText.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
        
        //999 人气  > 老师名字
        if (focusStrAttrsSize.width > nicknameLabelAttrsSize.width) {
            self.navigationBarLayoutSubviews()
        }
    }
    func navigationBarLayoutSubviews()
    {
        let nicknameLabelText:NSString = self.navigationBar.nicknameLabel.text! as NSString

        let nicknameLabelAttrsSize: CGSize = nicknameLabelText.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
        
        var focusWidth:CGFloat = 0
        if (self.livingSDK.roomInfo.pageConfig.focus.enable) {
            focusWidth = 0 + 7 + 40
            self.navigationBar.attentionButtonbackgroundColor.isHidden = false
            self.navigationBar.attentionButton.isHidden = false
        }
        
        let zhuboViewWidth:CGFloat = 45 + nicknameLabelAttrsSize.width + 8 + focusWidth;
        
        if (self.isNotchScreen) {
            self.navigationBar.zhuboView.frame = CGRect(x: 10, y: self.navigationBar.mNavigationbarHeight, width: zhuboViewWidth, height: 40)
           
        }else{
            self.navigationBar.zhuboView.frame = CGRect(x: 10, y: 10, width: zhuboViewWidth, height: 40)
        }
        self.navigationBar.layoutSubviews()
        self.updatesAnnouncementViewFrame()
    }
    func updatesAnnouncementViewFrame()
    {
        var announcementViewY:CGFloat = self.navigationBar.invitationList.frame.maxY + 10
        
        if (self.navigationBar.announceRollView.isHidden == false ) {
            announcementViewY = self.navigationBar.announceRollView.frame.maxY + 10
        }
        
        self.announcementView.frame = CGRect(x: self.announcementView.frame.origin.x, y: announcementViewY, width: self.announcementView.frame.size.width, height: self.announcementView.frame.size.height)
    }
    /**单体禁言 YES
      单体解禁言 NO
     */
    func onChatDisable(_ state: Bool) {
        if (state) {
            
            
            self.setCenter.livingTool.chatBar.attributedPlaceholder  = NSMutableAttributedString.getAttributed(string: "已被禁言", font: UIFont.PingFang(size: 14), foregroundColor: UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1))
            self.setCenter.livingTool.chatBar.isUserInteractionEnabled = false
            self.setCenter.livingTool.chatBarButton.isUserInteractionEnabled = false
            self.TF_toast( "你已被禁言")
        
        }else{
           
            self.setCenter.livingTool.chatBar.attributedPlaceholder  = NSMutableAttributedString.getAttributed(string: "说点什么", font: UIFont.PingFang(size: 14), foregroundColor: UIColor(red: 238/255.0, green: 244/255.0, blue: 248/255.0, alpha: 1));
            self.setCenter.livingTool.chatBar.isUserInteractionEnabled = true
            self.setCenter.livingTool.chatBarButton.isUserInteractionEnabled = true
            self.TF_toast( "禁言已解除")

        }
    }
    ///TODO:  全体解禁言
    func onChatDisableAll(_ state: Bool) {
        self.onChatDisable(state)
            //禁言
        if (state) {
            self.TF_toast( "全体禁言已开启")
        }else{
            if (self.livingSDK.roomInfo.isDisableall) {
                self.TF_toast( "全体禁言已关闭")
           
            }
           
        }
    }
    
    //TODO: 关闭抽奖时调用
   @objc func deleteBtnClicked()
    {
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.lotteryVC!.view.alpha = 0.0;
        } completion: { Bool in
            self.lotteryVC!.view.removeFromSuperview()
            self.lotteryVC = nil;

        }

    }
    //TODO: 关闭中奖列表
    @objc func closelistLotterVC()
    {
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.listLotteryVC!.view.alpha = 0.0;
        } completion: { Bool in
            
            self.listLotteryVC!.view.removeFromSuperview()
            self.listLotteryVC = nil;
            
            self.myLotteryVC!.view.removeFromSuperview()
            self.myLotteryVC = nil;
            
        }
    }
    ///TODO:  TFMyLotteryViewControllerDelegate 点击了查询中奖列表
    func getlottoryList() {
        //删除中奖人
        self.myLotteryVC!.view.removeFromSuperview()
        self.myLotteryVC = nil;
        //删除抽奖开始
        self.lotteryVC!.view.removeFromSuperview()
        self.lotteryVC = nil;
        
        self.view.addSubview(self.listLotteryVC!.view)
        self.listLotteryVC!.tableview.reloadData()

    }
    //TODO: TFLotteryViewControllerDelegate- 转盘结束回调结果
    func updateLotterView(winner:Bool,pub:Bool)
    {
        self.setCenter.lotteryCall.isHidden = true
        self.setCenter.layoutSubviews()
       
        //删除抽奖开始
        self.lotteryVC!.view.removeFromSuperview()
        self.lotteryVC = nil;
        
        self.view.addSubview(self.myLotteryVC!.view)
        if (winner) {
            
            self.myLotteryVC!.createwinnerView()
            
        } else {
            self.myLotteryVC!.createNOwinnerView()

        }
        let prize_name:NSString = self.prize_name
        if (prize_name.length > 0) {
            self.myLotteryVC!.winnerLab.text = prize_name as String
            self.myLotteryVC!.winnerIMg.isHidden = false
            self.myLotteryVC!.nowinnerIMg.isHidden = false
        } else {
            self.myLotteryVC!.winnerIMg.isHidden = true
            self.myLotteryVC!.nowinnerIMg.isHidden = true
        }
        self.myLotteryVC!.winnerBtn.isHidden = !pub
        self.myLotteryVC!.nowinnerBtn.isHidden = !pub
    }
    //TODO:  抽奖结束
    func onLotteryStop(_ result: TFLotteryStop) {
        if (self.setCenter.lotteryCall.isHidden) {
            self.setCenter.lotteryCall.isHidden = false
            self.setCenter.layoutSubviews()
          
        }
       
        //删除抽奖中的动画
        self.lotteryVC!.view.removeFromSuperview()
        self.lotteryVC = nil;
        
        self.listLotteryVC!.listData.removeAllObjects()
        self.view.endEditing(true)
        
        ///**奖品名称*/
        self.prize_name = result.prize_name as NSString;
        //中奖人是否有自己
        var  isMe:Bool = false
        for i in 0..<result.winnerList.count {
            let dict = result.winnerList[i] as! TFLotteryWinner

            if (dict.isMe) {
                isMe = true
                break;
            }
        }
     
        //聊天有中奖信息
        if(isMe||result.pub)
        {
            var nickname:NSString = ""
            
            self.listLotteryVC!.listData.addObjects(from: result.winnerList as! [Any])

            for i in 0..<result.winnerList.count {

                let nameDict = result.winnerList[i] as! TFLotteryWinner
                var inx:NSString = "";
                if ( i < 10) {
                    inx  = (inx as String) + "0" as NSString
                }
                inx = (inx as String) + (NSString.init(format: "%i.", i+1) as String) as NSString

                inx = "  " + (inx as String) as NSString
                
                let name:NSString = nameDict.nickname as NSString
                
                nickname = (nickname as String) + (inx as String) + (name as String) as NSString
            }

        }
        self.lotteryVC!.view.alpha = 1.0
        self.view.addSubview(self.lotteryVC!.view)
        ///是否中奖
        if (isMe) {
            self.lotteryVC!.iswinner = true
        } else {
            self.lotteryVC!.iswinner = false
        }
        //是否公布
        if (result.pub) {
            self.lotteryVC!.ispub = true
        } else {
            self.lotteryVC!.ispub = false
        }
        self.lotteryVC!.lotteryStopUI()
     
    }
    //TODO:  抽奖开始
    func onLotteryStart(_ result: TFLotteryStart) {
        self.setCenter.lotteryCall.isHidden = false
        self.setCenter.layoutSubviews()
       
        //删除中奖人
        self.myLotteryVC!.view.removeFromSuperview()
        self.myLotteryVC = nil;
        //删除中奖人列表
        self.listLotteryVC!.view.removeFromSuperview()
        self.listLotteryVC = nil;
        
        self.view.endEditing(true)

        self.lotteryVC!.view.alpha = 1.0;
        self.view.addSubview(self.lotteryVC!.view)
       
        self.lotteryVC!.lotteryStartUI()
    }
    
    
    func questionBtndrawRedDot()
    {
        //未弹起来
        if(self.setCenter.isShowAsk == false)
        {
            if(self.setCenter.moreConfiguration.questionBtn != nil)
            {
                self.setCenter.moreConfiguration.questionBtn!.number = self.setCenter.moreConfiguration.questionBtn!.number+1
                
                self.setCenter.moreConfiguration.questionBtn!.drawRedDotWidthNumber(self.setCenter.moreConfiguration.questionBtn!.number)
                
                self.setCenter.livingTool.more.drawRedDot()
            }
         
            
    
        }
        
    }
    //清空 提问 的未读数
    func questionBtnClearRedDot()
    {
        if(self.setCenter.moreConfiguration.questionBtn != nil)
        {
            self.setCenter.moreConfiguration.questionBtn!.clearRedDot()
        }
        
        
        self.unreadUI()
        
    }

    func unreadUI()

    {
        var new_unread:NSInteger = 0
        
        
        
        for i in 0..<self.setCenter.service.page1.customerServiceDict.count {

            let keys = self.setCenter.service.page1.customerServiceDict.allKeys
     
           let key = keys[i];
            let model:TF_CustomerService = self.setCenter.service.page1.customerServiceDict[key] as! TF_CustomerService
            //未读信息数
            new_unread = new_unread + model.unread
        
        
        }
        
        if(new_unread > 0 )
        {
      
            if(self.setCenter.moreConfiguration.customerServiceBtn != nil)
            {
                self.setCenter.moreConfiguration.customerServiceBtn!.drawRedDotWidthNumber(new_unread)
            }
            
            
        }else
        {
            if(self.setCenter.moreConfiguration.customerServiceBtn != nil)
            {
                self.setCenter.moreConfiguration.customerServiceBtn!.clearRedDot()
            }
        }
        
        if(new_unread == 0 )
        {
            if(self.setCenter.moreConfiguration.questionBtn != nil && self.setCenter.moreConfiguration.questionBtn!.number == 0)
            {
                self.setCenter.livingTool.more.clearRedDot()
            }else
            {
                self.setCenter.livingTool.more.clearRedDot()
            }
           
        }
    }
    
    
    //TODO:  提问审核通过
    public func onQuestionAudit(_ result: TFQuestionData) {
        self.setCenter.ask.addQskQuestionsDictUI(model: result)
        self.questionBtndrawRedDot()
    }
    //TODO:  接收别人的提问
    public func onQuestionAsk(_ result: TFQuestionData) {
        self.setCenter.ask.addQskQuestionsDictUI(model: result)
        self.questionBtndrawRedDot()
    }
    //TODO:  提问删除
    public func onQuestionDelete(_ result: TFQuestionData) {
        self.setCenter.ask.replyTodeleteUI(model: result)
    }
    //TODO: 主播回答了问题
    public func onQuestionReply(_ result: TFQuestionData) {
        self.setCenter.ask.questionPeplyUI(model: result)
        self.questionBtndrawRedDot()
    }
    //TODO:   删除投票的事件回调------
    public func onVoteDel(_ result: TFVoteData) {
        self.livingSDK.getVotingList {[weak self] (code, list, error) in
            guard let `self` = self else { return }
            if (code == 0 ) {
                if ( list!.count == 0 ) {
                    self.setCenter.voteButton.isHidden = true
                    self.voteView.isShowScrollView(show: false)
                    
                }else{
                    self.setCenter.voteButton.isHidden = false;
                }
                self.setCenter.layoutSubviews()
                
            }
        }
        
    }
    //TODO:  提交投票答案
    @objc func submitClick()
    {
        let model = TFSubmit()
        for i in 0..<self.voteView.scrollView.list.count {

            let model1111 = self.voteView.scrollView.list[i] as! TFOp
            if (model1111.selected) {
                model.option.add(NSString.init(format: "%i", i))
            }
        }
        model.vid = self.voteView.scrollView.result!.vid
        
        self.livingSDK.voteSubmit(model) { [weak self] (code, error) in
            guard let `self` = self else { return }
       
            if (code == 0) {
                self.voteView.scrollView.setContentOffset(CGPoint(x: self.voteView.scrollView.frame.size.width*2, y: 0), animated: false)
          
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
    
                    self.voteView.isShowScrollView(show: false)
                 
                }
            }else{
                self.TF_toast( error!.msg )
            }
        }
        
    }
    //TODO:  选中投票cell , 获取详情
    func voteDidSelectRowAtIndexPath(_ model: TFVoteData) {
        
        
        self.livingSDK.getVotingDetails(model.vid) {[weak self] (code, data, error) in
            guard let `self` = self else { return }
            if (code == 0 ) {
                self.voteView.scrollView.setContentOffset(CGPoint(x: self.voteView.scrollView.frame.size.width, y: 0), animated: false)
                
                self.voteView.scrollView.voteDetail(result: data!)
            
            }else{
                self.TF_toast( error!.msg)
            }
        }
       
    }
    //TODO: 投票结束的事件回调
    public func onVotePub(_ result: TFVoteData) {
        self.voteView.isShowScrollView(show: true)
        self.voteView.scrollView.setContentOffset(CGPoint(x: self.voteView.scrollView.frame.size.width, y: 0), animated: false)
       
        self.setCenter.voteButton.isHidden = false
        self.setCenter.layoutSubviews()
       
        self.voteView.scrollView.voteDetail(result: result)

    }
    //TODO:  -投票开始的事件回调
    public func onVoteNew(_ result: TFVoteData) {
        self.onVotePub(result)
    }
    //TODO: 签到倒计时结束 TF_SignInDelegate
    func signEnd() {
        self.setCenter.rollCall.isHidden = true
        self.setCenter.layoutSubviews()
    }
    //TODO:  - 结束签到的事件回调
    public func onSignEnd(_ result: TFSignEnd) {
        self.setCenter.rollCall.isHidden = true
        self.setCenter.layoutSubviews()
        self.signInView.onSignEndUI(result: result)
    
        self.TF_toast( "点名结束")
    
    }
    //TODO:  - 接收主播发起签到的事件回调
    public func onSignNew(_ result: TFSignNew) {
        self.setCenter.rollCall.isHidden = false
        self.setCenter.layoutSubviews()
        self.signInView.onSignNewUI(result: result)
   
    }
    
    //TODO:  推送公告的事件回调
    public func onAnnouncement(_ result: TFAnnouncement) {
        self.updatesAnnouncementViewFrame()
       
        self.announcementView.alpha = 1;
        self.announcementView.setAnnouncement(result: result)
      
    }
    //TODO:  ----- 接收滚动通知事件回调--------------
    public func onAnnounceRoll(_ result: TFAnnounceRoll) {
        self.navigationBar.announceRollView.initUI(content: result.content as NSString, link: result.link as NSString, duration: result.duration)
        
        self.updatesAnnouncementViewFrame()
  
    }
    //TODO: 当前用户被踢出出房间的事件回调
    func onMemberKick() {
        self.view.endEditing(true)
        
        let alert = UIAlertController.init(title: "提示", message: "你已被请出直播间", preferredStyle:.alert)

        let otherAction:UIAlertAction = UIAlertAction.init(title: "确认", style: .default) { action in
            self.exit()
        }
        alert.addAction(otherAction)
    
        if  UIDevice.current.model.hasPrefix("iPad") {
            alert.popoverPresentationController?.sourceView = self.view
            alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        }
        
        self.present(alert, animated: true)
    }
    //TODO: 商品列表的事件回调  商品状态变更时会实时更新列表
    func onGoodsUpdate(_ goodsList: NSMutableArray) {
        self.recommendList.removeAllObjects()
     
        for i in 0..<goodsList.count {
         let goods = goodsList[i] as! TFgoods
            // 推荐商品  上架的
            if (goods.putaway == TalkfunPutawayOn || goods.putaway == TalkfunPutawayRecommendOn) {
                self.recommendList.add(goods)

            }
        }
//        self.setCenter.recommendView.addUpdate(list: self.recommendList)
        self.goodsListViewUI(self.recommendList)
    }
    //TODO: 监听宣传图入口开关控制
    func onPopUp(_ popUp: TFPageConfigGlobalSwitchPopUp)
    {
        self.publicityUI(popUp)
    }
    //TODO: 推送弹窗广告的事件回调
    public func onPopupPut(_ result: TFPopupPut) {
        self.popupPutView.countdown.isHidden = false
        self.popupPutView.addPopupPut(result: result)
    }
    //TODO: 修改推送弹窗广告
    public func onPopupUpt(_ popUpList: NSMutableArray) {
        
        self.publicityView.updateData(popUpList)
        
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.setCenter.moreConfiguration.isShowConfiguration = false
        self.setCenter.isShowNetworkSelection = false
        self.setCenter.isShowInfo = false
        if (self.setCenter.ask.isShowAsk) {
            
        }else{
            self.setCenter.isShowAsk = false
        }
        
        self.setCenter.isShowService = false
        
        if (self.setCenter.reportView.isShowReport) {
            
        }else{
            self.setCenter.isShowReport = false
        }
        self.pull_upView.isShow(value: false)
      

        self.setCenter.isShowGoodsListView = false
        self.setCenter.isShowCourseDown = false
        self.view.endEditing(true)
        
    }
    
    //#pragma mark 直播间模式切换
    func onLiveModeChange(_ status: TFLiveModeChange) {
        if (status.currentMode == TalkfunLiveModeDesktop) {
            self.voiceLive.isHidden = true
            self.desktopContainerView.isHidden = false
            self.livingSDK.scalingMode = .aspectFit
        }else{
            self.livingSDK.scalingMode = .fill
            
            
            if (self.livingSDK.roomInfo.isCamera == false){
                self.voiceLive.isHidden = false
            }
           
            self.desktopContainerView.isHidden = true
        }
    }
    func onCameraShow() {
        self.voiceLive.isHidden = true
    }
    func onCameraHide() {
        self.voiceLive.isHidden = false
    }
    //#pragma mark 实时课件下载开关状态
    public func onDocumentDownload(_ enable: Bool) {
        //课件下载开关入口
        if (enable) {
            self.setCenter.moreConfiguration.courseDownShow = true
        } else{
            self.setCenter.moreConfiguration.courseDownShow = false
        }
        self.setCenter.moreConfiguration.updateData()
        
    }
    //TODO: SDK初始化回调----------------------------------
    func onEnterRoom(_ code: Int, result error: TFError) {
        //初始化成功
        if (code == 0 ) {

//            print(self.livingSDK.roomInfo.liveMode)
            //TODO: 读取老师名字与头像
            self.navigationBar.avatarImage.sd_setImage(with: URL.init(string: self.livingSDK.roomInfo.zhubo.avatar))
           
        
            var nickname:NSString = self.livingSDK.roomInfo.zhubo.nickname as NSString
            if (nickname.length > 5 ) {
                
                nickname =  nickname.substring(with:NSRange(location: 0, length: 5)) as NSString
                nickname =   (nickname as String) + "..." as NSString
               
            }
            
            self.navigationBar.nicknameLabel.text  = nickname as String
            
            //+7 +40  关注的二维码
            self.tfAlertView.attentionView.QRView.sd_setImage(with: URL.init(string: self.livingSDK.roomInfo.pageConfig.focus.url))

            //窗口弹出
            if (self.livingSDK.roomInfo.pageConfig.focus.enable && self.livingSDK.roomInfo.pageConfig.focus.popUp) {
                self.tfAlertView.attentionView.isHidden = false
            }else{
                self.tfAlertView.attentionView.isHidden = true
            }
            //TODO: 关注按钮
            self.navigationBarLayoutSubviews()
        
            let backgroundUrl:NSString = self.livingSDK.roomInfo.pageConfig.background.url as NSString
            //TODO:背景图
            if (self.livingSDK.roomInfo.pageConfig.background.enable && backgroundUrl.length > 0 ) {
                self.backgroundColorImageView.sd_setImage(with: URL.init(string: backgroundUrl as String as String) ,placeholderImage: UIImage.init(named: "HTLive.bundle/LivingackgroundColorImageView"))
               
            }
            //TODO:榜单开关
            if (self.livingSDK.roomInfo.pageConfig.invitationList.enable) {
                self.navigationBar.invitationList.isHidden = false
            }else
            {
                self.navigationBar.invitationList.isHidden = true
            }
            //TODO:邀请分享观看开关
            if (self.livingSDK.roomInfo.pageConfig.inviteRanking.enable) {
                self.setCenter.inviteEntrance.isHidden = false;
            }else
            {
                self.setCenter.inviteEntrance.isHidden = true;
            }
            
            //TODO:点赞功能开启
            if (self.livingSDK.roomInfo.pageConfig.like.enable) {
                self.setCenter.livingTool.showLive = true
            }else{
                self.setCenter.livingTool.showLive = false
            }
            //TODO:提问 真正的开关
            if (self.livingSDK.roomInfo.pageConfig.menu.question.enable) {
                self.setCenter.moreConfiguration.questionShow = true
            }else{
                self.setCenter.moreConfiguration.questionShow = false
            }
            //TODO:线路切换
            if (self.livingSDK.roomInfo.pageConfig.menu.liveLine) {
                self.setCenter.moreConfiguration.liveLineShow = true
            }else{
                self.setCenter.moreConfiguration.liveLineShow = false
            }
            //TODO:宝贝 链接
            if (self.livingSDK.roomInfo.pageConfig.store.enable) {
                self.setCenter.livingTool.showLivingaBby = true
            }else{
                self.setCenter.livingTool.showLivingaBby = false

            }
            //TODO:菜单入口
            if (self.livingSDK.roomInfo.pageConfig.menu.enable) {
                self.setCenter.livingTool.showPull_up = true
            }else{
                self.setCenter.livingTool.showPull_up = false
            }
            //TODO:个人中心
    //        if (self.livingSDK.roomInfo.pageConfig.menu.info) {
    //            self.setCenter.moreConfiguration.infoShow = YES;
    //        }else{
    //            self.setCenter.moreConfiguration.infoShow = NO;
    //        }
            //TODO:红_包
    //        if (self.livingSDK.roomInfo.pageConfig.menu.redPackRecord) {
    //            self.setCenter.moreConfiguration.redPackRecordShow = YES;
    //        }else{
    //            self.setCenter.moreConfiguration.redPackRecordShow = NO;
    //        }
    //        //TODO:提_现
    //        if (self.livingSDK.roomInfo.pageConfig.menu.withdraw) {
    //            self.setCenter.moreConfiguration.withdrawShow = YES;
    //        }else{
    //            self.setCenter.moreConfiguration.withdrawShow = NO;
    //        }
            //TODO:商_城
            if (self.livingSDK.roomInfo.pageConfig.menu.store.enable) {
                self.setCenter.moreConfiguration.storeShow = true
            }else{
                self.setCenter.moreConfiguration.storeShow = false;
            }
            //TODO:客服
            if (self.livingSDK.roomInfo.pageConfig.service.enable) {
                self.setCenter.moreConfiguration.serviceShow = true
            }else{
                self.setCenter.moreConfiguration.serviceShow = false
            }
            //TODO:举报
            if (self.livingSDK.roomInfo.pageConfig.menu.report) {
                self.setCenter.moreConfiguration.reportShow = true
            }else{
                self.setCenter.moreConfiguration.reportShow = false
            }
            //TODO:邀请分享
    //        if (self.livingSDK.roomInfo.pageConfig.inviteRanking.enable) {
    //            self.setCenter.livingTool.inviteRankingShow = YES;
    //        }else{
    //            self.setCenter.livingTool.inviteRankingShow = NO;
    //        }
            self.voiceLive.avatar.sd_setImage(with: URL.init(string: self.livingSDK.roomInfo.zhubo.avatar))
           
            self.setCenter.info.avatar.sd_setBackgroundImage(with: URL.init(string: self.livingSDK.roomInfo.myInfo.avatar), for: .normal)
           
            self.setCenter.info.nickName.text = self.livingSDK.roomInfo.myInfo.nickname
            
            //课件下载开关入口
            self.onDocumentDownload(self.livingSDK.roomInfo.pageConfig.global.glswitch.document.enable)
        
            

            //判断是否已经打开了功能
            if (self.setCenter.moreConfiguration.tempArray.count > 0 ) {
                self.setCenter.livingTool.moreShow = true
            }else{
                self.setCenter.livingTool.moreShow = false
            }
            self.setCenter.livingTool.showAll()
         
            
            //TODO:选项卡 PPT  聊天
    //        if (self.livingSDK.roomInfo.pageConfig.menu.tabsDataList.count > 0 ) {
            self.pull_upView.initUI(tabsDataList: self.livingSDK.roomInfo.pageConfig.menu.tabsDataList)
            
            if (self.pull_upView.getPPTVIew() != nil) {
                self.livingSDK.configurePPTContainerView(self.pull_upView.getPPTVIew()!)
            }
           
          
          
            //TODO:上架与推荐的商品列表
            if (self.getGoodsList().count > 0 ) {
                self.setCenter.livingTool.livingaBbyLabel.text = NSString.init(format: "%lu", self.getGoodsList().count) as String
                
            
            }
            //TODO:推荐的商品列表
            if (self.getRecommendList().count > 0 ) {
                self.setCenter.recommendView.addUpdate(list: self.getRecommendList())
             

            }
            //TODO:直播间状态
            if (self.livingSDK.roomInfo.liveStatus == TalkfunLiveStatusStart) {
                self.navigationBar.adListView.isHidden = false
            }else{
                self.navigationBar.adListView.isHidden = true
            }
            //TODO:浮动广告列表
            if (self.livingSDK.roomInfo.pageConfig.ad.enable) {
                self.navigationBar.adListView.add(ADLidt: self.livingSDK.roomInfo.pageConfig.adlist as! [TFAdModel])
               
               
            }
            
            if (self.isMove == true) {
                self.move(self.isMove)
        
            }
            //TODO:获取投票列表
            self.livingSDK.getVotingList { [weak self] (code, list, error) in
                guard let `self` = self else { return }
         
                if (code == 0 ) {
                    if (list!.count == 0 ) {
                        self.setCenter.voteButton.isHidden = true
                    }else{
                        self.setCenter.voteButton.isHidden = false
                    }
                    self.setCenter.layoutSubviews()
                }else{
                    self.TF_toast( error!.msg )
                }
            }
            //TODO:获取默认点赞数
            self.setCenter.livingTool.updateTotal(total: self.livingSDK.roomInfo.likeResult.times)
     
     
            //TODO:摄像头开关
            if (self.livingSDK.roomInfo.isCamera == false && self.livingSDK.roomInfo.liveStatus == TalkfunLiveStatusStart) {
                self.voiceLive.isHidden = false
            }
         
            //广告宣传图入口!
            
            self.publicityUI(self.livingSDK.roomInfo.pageConfig.global.glswitch.popUp)
           
            
           //仅仅隐藏聊天输入栏, 聊天记录保留
            if (self.livingSDK.roomInfo.mod_text_live.config.chat.enable)
            {
                self.setCenter.livingTool.chatBar.isHidden = false
                self.setCenter.livingTool.chatBarButton.isHidden = false
            }else
            {
                
                self.setCenter.livingTool.chatBar.isHidden = true
                self.setCenter.livingTool.chatBarButton.isHidden = true
            }
            
            //仅仅隐藏提问输入栏的, 提问记录保留
            if (self.livingSDK.roomInfo.mod_text_live.config.qa.enable)
            {
                self.setCenter.ask.textViewButton.isHidden = false
                self.setCenter.ask.textView.isHidden = false
                self.setCenter.ask.askBtn.isHidden = false
                
            }else
            {
                self.setCenter.ask.textViewButton.isHidden = true
                self.setCenter.ask.textView.isHidden = true
                self.setCenter.ask.askBtn.isHidden = true
                
                
            }
            
            //--------------------------
            if(self.livingSDK.roomInfo.pageConfig.questionnaire.enable == true)
            {
                let img = self.livingSDK.roomInfo.pageConfig.questionnaire.icon.img
                let title = self.livingSDK.roomInfo.pageConfig.questionnaire.icon.title
                
                self.setCenter.informationCollection.sd_setImage(with: URL(string: img), for: .normal)
                self.setCenter.informationCollection.setTitle(title, for: .normal)
                
                self.setCenter.informationCollection.isHidden = false
                
                self.formationCollectionView.setModelUI(self.livingSDK.roomInfo.pageConfig.questionnaire)
            }else
            {
                self.setCenter.informationCollection.isHidden = true
            }
 
        }
        else{
            self.TF_toast( error.msg )
     
        }
    }

    // MARK: 学时防作弊
    func onPreventCheatingSign(inListener model: TFSignLoopPreventCheat) {

        if(self.preventCheatCountdown.remind.isShow==false)
        {
            self.preventCheatCountdown.remind.isShow = true
            self.preventCheatCountdown.remind.delegate = self
            self.preventCheatCountdown.remind.run(model: model)
            self.preventCheatCountdown.remind.playSound(name:"SuccessfulCheckSoundPop")
            self.view.addSubview(self.preventCheatCountdown)
        }

    }
    /**倒计时结束TalkfunPreventCheatCountdownViewDelegate**/
    func countdownEnds()
    {
        
        
        /**type | 0: 倒计时结束后发
            1: 继续学习*/
        self.livingSDK.preventCheatingSign(inType: 0) { code, error in
            
            
            
        }
        
        
    }
    /**继续学习*/
    func continueStudying(completion: @escaping (Int, String) -> Void) {
    
        
        self.livingSDK.preventCheatingSign(inType: 1) {[weak self] code, error in
            
            guard let `self` = self else { return }
            
            if(code==0)
            {
                var msg:String = ""
                if(error?.msg != nil)
                {
                    msg = error!.msg
                }
                completion(code,msg)
                
            }else
            {
                self.view.toast(error!.msg, position: CGPoint(x: UIScreen.main.bounds.width/2, y: self.view.frame.height/2))
                
          
            }
            
  
            
        }
    }
    
    // MARK: - 视频播放状态改变  -黑屏加菊花时用到
    func playerLoadStateDidChange(_ loadState:TalkfunPlayerLoadState) {
  
        if (loadState == TalkfunPlayerLoadState.stalled) {
               print("发生卡顿，显示菊花")
            self.activityIndicator.startAnimating()
            self.activityIndicator.isHidden = false;
            self.activityIndicator.frame = self.view.frame;
            self.view.addSubview(self.activityIndicator)
        }else
        {
            self.activityIndicator.stopAnimating()
             print("正常播放，移除菊花")
            self.activityIndicator.isHidden = true

        }
    }
    // MARK: - 视频窗口上的菊花
  
    lazy var activityIndicator:UIActivityIndicatorView = {

        if #available(iOS 13.0, *) {
            let act = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.white)

            act.isUserInteractionEnabled = false

            return act
        }else
        {
            let act = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.whiteLarge)

            act.isUserInteractionEnabled = false

            return act
        }
       
    }()
     //TODO: #pragma mark 发布随堂测试时
    public func onExaminationPush(_ result: TFQuestionnairePushResult) {
        let t = result.endTime
        if (result.type == TFExaminationTypeQuickAnswer) { //快速答题卡
            
            let params = TTFExaminationDetailParam()
            params.id = result.id;
            params.type = TFExaminationTypeQuickAnswer;
            
            self.livingSDK.getExaminationDetail(params) {[weak self] (code, result1, error )in
                guard let `self` = self else { return }
            
                if (code == 0) {
                    self.view.addSubview(self.answerCard!)
                    self.answerCard?.setAnswerCard(result1)
                  
                    self.answerCard?.answerCardId = result.id
                    self.answerCard?.addTimer(t)
                 
                }
            }
        }
    }
    //#pragma mark 主播提前-结束作答随堂测试
    public func onExaminationEnd(_ result: TFQuestionnaireEndResult) {
        if (  result.type == TFExaminationTypeQuickAnswer) {
            if (result.id == self.answerCard!.answerCardId) {
              
                self.endAnswerCardView()
            }
        }
    }
    //快速答题卡倒计时结束
    func endAnswerCardView()
    {
        self.answerCard!.frame = CGRect(x: (self.view.frame.size.width-125)/2.0, y: (self.view.frame.size.height-44)/2.0,width: 125, height: 44)
        
        self.answerCard!.countdownEndView.isHidden = false
        self.answerCard!.answerView.isHidden = true
        self.answerCard!.answerSuccessView.isHidden = true
        self.answerCard!.startAnswerCardSuccessTimers()
     
    }
    //个人中心点击了保存名字
    func save(_ name: NSString) {
        
    }
    /** 引起键盘*/
    func livingBabyClick() {
        self.chatBarView.chatBar.becomeFirstResponder()
        
    }
    //#pragma mark ----- 全屏图片 图片序列号-------------
    func fullScreenPicture(_ model: TF_LivingChatData) {
        self.rotatePictures.isHidden = false
        self.rotatePictures.setContentOffsetWithModel(model: model, animate: false)
        
    }
    //#pragma mark -- 宣传图代理回调
    func checkPuplicityImg(_ model: TFPopupPut) {
        self.popupPutView.countdown.isHidden = false
        self.popupPutView.addPopupPut(result: model)
        self.publicityView.showView(false)
    }
    //#pragma mark -- 记入课件详情的代理方法
    func checkCourseDetail(_ model: TFdoc) {
        let vc = TFdocumentPreviewController()
        vc.urlStr = model.url;
        vc.localPath = model.localPath;
        vc.hidesBottomBarWhenPushed = true;
        if self.navigationController != nil {
           self.navigationController?.pushViewController(vc, animated: true)
        }else
        {
            self.present(vc, animated: true)
        }
    }
    
    func move(_ isMove:Bool)
    {
        var moveX:CGFloat =  0
        if isMove==false {
            moveX = -self.view.frame.size.width
        }
       
        UIView.animate(withDuration: 0.5) {
            
            let  transformX = CGAffineTransform(translationX: moveX, y: 0)
                //向左移动的动画
                self.setCenter.chatRecord.transform = transformX
                self.navigationBar.view.transform = transformX
                self.setCenter.transform = transformX
         
            
        }
        self.isMove = !isMove
    }
    //打开链接
    public func marqueeClick() {
        
        let content:NSString = self.navigationBar.announceRollView.content.text! as NSString
        if (content.length > 0) {
            let url:NSString = self.navigationBar.announceRollView.url
            TalkfunSharedTools.openUrl(str: url)
            
         
        }
        
        
    }
    ////代理知道 , 关闭了通知
    func onCloseWinnersCLick() {
        self.updatesAnnouncementViewFrame()
    }
    
    func publicityUI(_ popUp:TFPageConfigGlobalSwitchPopUp)
    {
        if popUp.enable {
            self.setCenter.publicityBtn.isHidden = false
            
            self.setCenter.publicityBtn.setTitle(popUp.data.name, for: .normal)
            
            if popUp.data.image.count>0 {
                
                self.setCenter.publicityBtn.sd_setImage(with: URL.init(string: popUp.data.image), for: .normal)
              
            }
            
            self.publicityView.titleLab.text = popUp.data.title
        }else
        {
            self.setCenter.publicityBtn.isHidden = true
        }
  
    }
    // 控制器的view即将显示的时候调用
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        //开启
        if ((self.navigationController) != nil) {
        self.navigationController?.interactivePopGestureRecognizer!.isEnabled = false
        }
        self.TF_isStatusBarHidden = UIApplication.shared.isStatusBarHidden
        if self.TF_isStatusBarHidden == false {
            UIApplication.shared.isStatusBarHidden = true
        }
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if ((self.navigationController) != nil) {
            self.navigationController?.interactivePopGestureRecognizer!.isEnabled = true
        }
        UIApplication.shared.isStatusBarHidden = self.TF_isStatusBarHidden
    }
    // MARK: - 横竖屏支持
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return  UIInterfaceOrientationMask.portrait
    }
    //#pragma mark - 旋转
    override var shouldAutorotate: Bool{
        return false
    }
    ////隐藏状态栏
    override var prefersStatusBarHidden: Bool
    {
        return true
    }
    deinit {
            print("生活直播没有循环引用")
        }
}
